|
|
|
|
|
|
|
use the center of projection as the starting point. The direction vector leads from the center of projection through the pixel. If the center of projection is at (cx, cy, cz) and the pixel has coordinates (px, py, pz), the vector has components <px - cx, py - cy, pz - cz>. |
|
|
|
|
|
|
|
|
The points along this ray have coordinates given by (cx, cy, cz) + t * <px - cx, py - cy, pz - cz> for different values of t. For example, the X coordinate of a point on this ray is given by: |
|
|
|
 |
|
|
|
|
cx + t * (px - cx) |
|
|
|
|
|
|
|
|
where t >= 0. Values of t less than zero correspond to points behind the center of projection. |
|
|
|
|
|
|
|
|
To find the point where the ray intersects the nearest object, the program can calculate t for the point of intersection with each object. It then takes the intersection with the smallest positive value for t. |
|
|
|
|
|
|
|
|
To make it easier to handle different kinds of objects, you can create a RayTraceable class that defines the methods that an object must implement to be ray traced. The FindT function takes as parameters the ray's starting point and its direction vector. It returns the smallest positive values for t in the previous equations. |
|
|
|
|
|
|
|
|
For example, the equation for a sphere of radius R centered at position (cx, cy, cz) is: |
|
|
|
 |
|
|
|
|
(cx - x)2 + (cy - y)2 + (cz - z)2 - R2 = 0 |
|
|
|
|
|
|
|
|
You can write the equation of a line through point (px, py, pz) along the vector <vx, vy, vz> using parametric equations like this: |
|
|
|
 |
|
|
|
|
X(t) = px + t * vx
Y(t) = py + t * vy
Z(t) = pz + t * vz |
|
|
|
|
|
|
|
|
If you substitute these values into the equation for a sphere, you get: |
|
|
|
 |
|
|
|
|
(cx - px + t * vx)2 + (cy - py + t * vy)2 + (cz - pz + t * vz)2 - R2 = 0 |
|
|
|
|
|
|
|
|
After rearranging this a bit, you get: |
|
|
|
 |
|
|
|
|
A * t2 + B * t + C = 0 |
|
|
|
 |
|
|
|
|
A = vx2 + vz2 + vz2 B = 2 * vx * (px - cx) + 2 * vy * (py - cy) + 2 * vz * (pz - cz)
C = cx2 + cy2 + cz2 + px2 + py2 + pz2 - 2 * (cx * px + cy * py + cz * pz) - R2 |
|
|
|
|
|
|
|
|
The solutions to this equation are given by the quadratic formula as: |
|
|
|
 |
|
|
|
|
t = -B ± Sqr(B2 - 4 * A * C) / 2 / A |
|
|
|
|
|